<?php

namespace App\Http\Controllers\Pc;

use App\Http\Controllers\Controller;
use App\Models\AmazonPlanStatus;
use App\Models\AmazonSkulist;
use App\Models\BaseModel;
use App\Models\ResourceModel\AmazonBuhuoDetailModel;
use App\Models\ResourceModel\AmazonBuhuoRequestModel;
use App\Models\ResourceModel\TransportationMode;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Models\DigitalModel;
use App\Http\Controllers\Jobs\SavePdfController;
use Illuminate\Support\Facades\Redis;

class DigitalController extends Controller
{
    private $model;
    private $request;
    protected $amazonBuhuoRequestModel;
    protected $amazonBuhuoDetailModel;
    protected $transportationModeModel;
    public function __construct(Request $request)
    {
        $this->model = new DigitalModel();
        $this->request = $request;
        $this->amazonBuhuoRequestModel = new AmazonBuhuoRequestModel();
        $this->amazonBuhuoDetailModel = new AmazonBuhuoDetailModel();
        $this->transportationModeModel = new TransportationMode();
    }

    /**
     * 查询亚马逊补货预警数据
     */
    public function buhuoWarn_Data()
    {

        $params = $this->request->all();

        $result = $this->model->getBuhuoWarn($params);

        return $this->back('获取成功', '200', $result);
    }


    
    /**
     * 工厂直发仓补货预警数据
     */
    public function getFactoryBuhuo()
    {

        $params = $this->request->all();

        $result = $this->model->getFactoryBuhuo($params);

        return $this->back('获取成功', '200', $result);
    }

    
    /**
     * 工厂补货导入
     */
    public function Importfactory()
    {

        $params = $this->request->all();

        $result = $this->model->Importfactory($params);
        if($result['type']=='success'){
            return $this->back('获取成功', '200', $result);
        }else{
            return $this->back('导入失败'.$result['msg'], '500');
        }

    
    }
    

    /**
     * 工厂直发仓库存明细
     */
    public function getFactoryBuhuoNum()
    {

        $params = $this->request->all();

        $result = $this->model->getFactoryBuhuoNum($params);

        return $this->back('获取成功', '200', $result);
    }


    


    //获取下单id 
    public function getOrderListByCus()
    {
        $params = $this->request->all();

        $result = $this->model->getOrderListByCus($params);

        return $this->back('获取成功', '200', $result);
    }


    
    //获取合同下单数
    public function getCusNumByContract()
    {
        $params = $this->request->all();

        $result = $this->model->getCusNumByContract($params);
        

        if ($result['type'] == 'success') {
            return $this->back('获取成功', '200', $result);
        } else {
            return $this->back($result['msg'], '500');
        }

        // return $this->back('获取成功', '200', $result);
    }

    public function delete_data()
    {
        $res = DB::table('amazon_buhuo_request')
            ->where('request_time', '<', '2022-04-01')
            ->select('id')
            ->get();
        foreach ($res as $val) {
            DB::table('amazon_buhuo_detail')
                ->where('request_id', '=', $val->id)
                ->delete();
        }
    }

    /**
     * 亚马逊补货数据excel导入
     */
    public function replenish_Import()
    {
        $params = $this->request->all();

        $result = $this->model->replenish_ExcelImport($params);

        if ($result['type'] == 'success') {
            return $this->back('导入成功', '200', $result['msg']);
        } elseif ($result['type'] == 'attention') {
            return $this->back($result['msg'], '300');
        } else {
            return $this->back($result['msg'], '500');
        }
    }

    public function replenish_ExcelImport_confirm()
    {
        $params = $this->request->all();

        $result = $this->model->replenish_ExcelImport_confirm($params);

        if ($result['type'] == 'success') {
            return $this->back('导入成功', '200', $result['msg']);
        } else {
            return $this->back($result['msg'], '500');
        }
    }

    //补货excel导入后返回列表数据
    public function replenish_excel_list()
    {
        $params = $this->request->all();

        $result = $this->model->replenish_excel_list($params);
        if ($result['type'] == 'success') {
            return $this->back('导入成功', '200', $result);
        } else {
            return $this->back($result['msg'], '300');
        }

      

        // return $this->back('请求成功', '200', $result);

    }


    //补货excel导入后返回列表数据
    public function ReSendBuhuoRequest()
    {
        $params = $this->request->all();

        $result = $this->model->ReSendBuhuoRequest($params);
        if ($result['type'] == 'success') {
            return $this->back('提交成功', '200', $result);
        } else {
            return $this->back($result['msg'], '300');
        }

    }

    //自动计算补货公式
    public function AutoBuhuo(){
        $params = $this->request->all();

        $result = $this->model->AutoBuhuo($params);
        if ($result['type'] == 'success') {
            return $this->back('导入成功', '200', $result['msg']);
        } else {
            return $this->back($result['msg'], '300');
        }
    }
    /**
     * 查询亚马逊excel导入数据
     */
    public function amazonExcel_data()
    {

        $params = $this->request->all();

        $result = $this->model->getAmazonExcel($params);

        return $this->back('获取成功', '200', $result);
    }

    /**
     * 亚马逊品类数据-新增sku
     */
    public function add_sku()
    {

        $params = $this->request->all();

        $result = $this->model->addSku($params);

        if ($result['type'] == 'success') {
            return $this->back('新增成功', '200', $result['data']);
        } else {
            return $this->back('新增失败', '300', $result['msg']);
        }
    }

    /**
     * 亚马逊品类数据-修改sku
     */
    public function update_sku()
    {

        $params = $this->request->all();

        $result = $this->model->updateSku($params);

        if ($result['type'] == 'success') {
            return $this->back('修改成功', '200', $result['data']);
        } else {
            return $this->back('修改失败', '300', $result['msg']);
        }
    }

    /**
     * 更新skulist
     */
    public function update_skulist()
    {

        $params = $this->request->all();

        $result = $this->model->updateSkulist($params);

        return $this->back('获取成功', '200', $result);
    }

    public function del_skulist(){
        $params = $this->request->all();

        $id = $params['Id'];

        $delete = DB::table('amazon_skulist')->where('id',$id)->delete();

        if($delete){
            return $this->back('删除成功', '200');
        }else{
            return $this->back('删除失败', '500');
        }


    }

    /**
     * 更新skulistimg
     */
    public function update_skulist_img()
    {

        $params = $this->request->all();

        $result = $this->model->updateSkulistImg($params);

        if ($result['type'] == 'success') {
            return $this->back('修改成功', '200', $result['data']);
        } else {
            return $this->back('修改失败', '300', $result['msg']);
        }
    }

    
    /**
     * 查询shopee商品链接excel导入数据
     */
    public function shopeeExcel_link()
    {

        $params = $this->request->all();

        $params['type'] = 'goods_link';

        $result = $this->model->getShopeeExcel($params);

        return $this->back('获取成功', '200', $result);
    }

    /**
     * 查询shopee商品广告excel导入数据
     */
    public function shopeeExcel_adv()
    {

        $params = $this->request->all();

        $params['type'] = 'goods_adv';

        $result = $this->model->getShopeeExcel($params);

        return $this->back('获取成功', '200', $result);
    }

    /*
     * excel导入方法
     * type：excel来源
     * params：上传的文件
     */
    public function excel_insert()
    {

        $params = $this->request->all();
        $result = $this->model->excelInsert($params);

        if ($result['type'] == 'success') {
            return $this->back('导入成功', '200', $result['msg']);
        } else {
            return $this->back($result['msg'], '300');
        }
    }

    //excel导出方法
    public function excel_postExport()
    {

        $params = $this->request->all();

        if ($params['export_type'] == 'buhuo_warning') {

            $result = $this->model->amazon_warnExport($params);

            return $this->back('导出成功', '200', $result['msg']);
        }

    }


    //excel导出方法
    public function excel_getExport()
    {

        $params = $this->request->all();

        if ($params['export_type'] == 'category') {
            $this->model->amazon_categoryExport($params);
        }

    }

    //获取亚马逊所有品类
    public function getProducetType()
    {
        $where = "1 = 1";
        $sql = "select id,product_typename from amazon_category where $where";
        $data = DB::select($sql);
        if ($data) return $this->back('获取成功', '200', $data);
    }

    //获取亚马逊所有销售状态
    public function getSalesType()
    {
        $where = "1 = 1";
        $sql = "select id,category_status from amazon_category_status where $where";
        $data = DB::select($sql);
        if ($data) return $this->back('获取成功', '200', $data);
    }

    //获取所有运营人员
    public function getUser()
    {
        $params = $this->request->all();
        $is_ys = $params['is_ys']??false;
        if($is_ys){
            $organize_id = db::table('organizes')->where('name','like','%包装部%')->first()->Id;
           $data=  db::table('organizes_member as a')->leftjoin('users as b','a.user_id','=','b.Id')->where('a.organize_ids','like','%'.$organize_id.'%')->select('b.account','b.Id','b.state')->get();
        }else{
            $where = "1 = 1";
            if(isset($params['key'])) {
                $key = $params['key'];
                $where .= " and account like '%$key%'";
            }
            $sql = "select account,Id,state from users where $where order by state asc";
    
    //        $sql = "select a.account,a.Id from users a left join organizes_member b on a.Id=b.user_id where $where";
            $data = DB::select($sql)??'';
            foreach ($data as $k=>$v){
                if($v->state==2){
                    $data[$k]->account = $v->account.'(已离职)';
                }
            }
        }

        return $this->back('获取成功', '200', $data);
    }

    //批量修改亚马逊销售计划增长倍数
    public function updatePlan()
    {
        $params = $this->request->all();
        $id = $params['select_id'];
        $planNum = $params['plan'];
        $where = "id in ($id)";
        $sql = "update amazon_skulist set plan_multiple={$planNum} where $where";
        $data = DB::update($sql);
        if ($data !== false) return $this->back('请求成功', '200', '修改成功，已重新计算');
    }

    public function set_fba_id()
    {
        $shop_name = DB::table('shop')->where('platform_id', '=', 5)->select('Id', 'shop_name')->get();
        foreach ($shop_name as $val) {
            $shop_name = $val->shop_name;
            $id = $val->Id;
            $sql = "select `id`,`name` from saihe_warehouse where `name` like '%{$shop_name}%'";
            $res = DB::select($sql);
            if (!empty($res)) {
                $fba_id = $res[0]->id;
                $result = DB::table('shop')->where('Id', '=', $id)->update(['fba_warehouse_id' => $fba_id]);
                if ($result) var_dump($fba_id);
            }
        }

        
    }

    //补货预警自动补货单
    public function create_buhuoDoc_auto(){
        $params = $this->request->all();

        $result = $this->model->create_buhuoDoc_auto($params);

        $this->AddSysLog($params,$result,'补货预警自动补货单',__METHOD__);

        if ($result['type'] == 'success') {
            return $this->back('请求成功', '200', $result);
        } else{
            return $this->back($result['data'], '300');
        }
    }

    //更改任务名
    public function UpdateTaskName(){
        $params = $this->request->all();

        $result = $this->model->UpdateTaskName($params);

        if ($result['type'] == 'success') {
            return $this->back('请求成功', '200', $result);
        } else{
            return $this->back('该任务名重复', '300');
        }
    }

    

    //根据补货计划生成补货单
    public function amazon_buhuo_plan()
    {
        $params = $this->request->all();
        $result = $this->model->create_buhuoDoc($params);
        if ($result['type'] == 'success') {
            return $this->back($result['msg'], '200', $result['data']);
        } elseif ($result['type'] == 'stock') {
            return $this->back($result['msg'], '400', $result['data']);
        } else {
            return $this->back($result['msg'], '300');
        }
    }

    //回填走船时间，到港时间
    public function UpBuhuoBoat_time()
    {
        $params = $this->request->all();
        $result = $this->model->UpBuhuoBoat_time($params);
        if ($result['type'] == 'success') {
            return $this->back('修改成功', '200', $result);
        }else {
            return $this->back('修改失败', '300');
        }
    }

    

    //生成理货标签
    public function SendLhLabel()
    {
        $params = $this->request->all();
        $result = $this->model->SendLhLabel($params);
        if ($result['code'] == '200') {
            return $this->back('请求成功', '200', $result);
        } else{
            return $this->back('请求失败', '300',$result);
        }
    }
    
    //直发仓补货任务合并导出
    public function FactoryPlanExport()
    {
        $params = $this->request->all();
        $result = $this->model->FactoryPlanExport($params);
        if ($result['type'] == 'success') {
            return $this->back('请求成功', '200', $result);
        } else{
            return $this->back('加入队列失败', '300',$result);
        }
    }
    

    //直发仓补货任务
    public function amazon_buhuo_planb()
    {
        $params = $this->request->all();
        $result = $this->model->create_buhuoDocb($params);
        if ($result['type'] == 'success') {
            return $this->back($result['msg'], '200', $result['data']);
        } elseif ($result['type'] == 'stock') {
            return $this->back($result['msg'], '400', $result['data']);
        } else {
            return $this->back($result['msg'], '300');
        }
    }


    //直发仓补货任务-新
    public function amazon_buhuo_plan_new()
    {
        $params = $this->request->all();
        $result = $this->model->amazon_buhuo_plan_new($params);
        if ($result['type'] == 'success') {
            return $this->back($result['msg'], '200', $result['data']);
        } elseif ($result['type'] == 'stock') {
            return $this->back($result['msg'], '400', $result['data']);
        } else {
            return $this->back($result['msg'], '300');
        }
    }


    
    //直发仓补货任务-自动装箱
    public function GetFactoryautoBoxLog()
    {
        $params = $this->request->all();
        $result = $this->model->GetFactoryautoBoxLog($params);
        return $this->back('请求成功', '200', $result);
    }
    
  
    //直发仓补货任务-自动装箱
    public function FactoryautoBox()
    {
        $params = $this->request->all();
        $result = $this->model->FactoryautoBox($params);
        return $this->back('请求成功', '200', $result);
    }

    //直发仓补货任务-自动装箱余数
    public function FactoryOtherBox()
    {
        $params = $this->request->all();
        $result = $this->model->FactoryOtherBox($params);
        return $this->back('请求成功', '200', $result);
    }
    
    
    //直发仓补货任务-装箱详情
    public function FactoryInsertBoxDetail()
    {
        $params = $this->request->all();
        $result = $this->model->FactoryInsertBoxDetail($params);
        return $this->back('请求成功', '200', $result);
    }

    public function FactoryInsertBoxDetailList()
    {
        $params = $this->request->all();
        $result = $this->model->FactoryInsertBoxDetailList($params);
        if($result['type']=='fail'){
            return $this->back($result['msg'], '500' );
        }else{
            return $this->back('请求成功', '200', $result);
        }
    }

    public function FactoryInsertBoxDetailBySpuList()
    {
        $params = $this->request->all();
        $result = $this->model->FactoryInsertBoxDetailBySpuList($params);
        return $this->back('请求成功', '200', $result);
    }

    //删除排柜  
    public function FactoryDelChest()
    {
        $params = $this->request->all();
        $result = $this->model->FactoryDelChest($params);
        if($result['type']=='fail'){
            return $this->back($result['msg'], '500' );
        }else{
            return $this->back('请求成功', '200', $result);
        }
    }

    //更改排柜
    public function FactoryUpdateChest()
    {
        $params = $this->request->all();
        $result = $this->model->FactoryUpdateChest($params);
        if($result['type']=='fail'){
            return $this->back($result['msg'], '500' );
        }else{
            return $this->back('请求成功', '200', $result);
        }
    }

    // 排柜列表
    public function FactoryChestList()
    {
        $params = $this->request->all();
        $result = $this->model->FactoryChestList($params);
        return $this->back('请求成功', '200', $result);
    }

    //修改排柜-spu
    public function UpdateFactoryBoxDetailSpu()
    {
        $params = $this->request->all();
        $result = $this->model->UpdateFactoryBoxDetailSpu($params);
        if($result['type']=='fail'){
            return $this->back($result['msg'], '500' );
        }else{
            return $this->back('请求成功', '200', $result);
        }
    }

    //修改排柜-spu-批量
    public function UpdateFactoryBoxDetailSpus()
    {
        $params = $this->request->all();
        $result = $this->model->UpdateFactoryBoxDetailSpus($params);
        if($result['type']=='fail'){
            return $this->back($result['msg'], '500' );
        }else{
            return $this->back('请求成功', '200', $result);
        }
       
    }

    //修改排柜-spu-批量
    public function UpdateFactoryBoxDetailRequest()
    {
        $params = $this->request->all();
        $result = $this->model->UpdateFactoryBoxDetailRequest($params);
        if($result['type']=='fail'){
            return $this->back($result['msg'], '500' );
        }else{
            return $this->back('请求成功', '200', $result);
        }
    }




    public function UpdateFactoryBoxDetail()
    {
        $params = $this->request->all();
        $result = $this->model->UpdateFactoryBoxDetail($params);
        if($result['type']=='fail'){
            return $this->back($result['msg'], '500' );
        }else{
            return $this->back('请求成功', '200', $result);
        }
    }

    
    //获取亚马逊补货单数据
    public function get_buhuoDoc()
    {
        $params = $this->request->all();

        $result = $this->model->select_buhuoDoc($params);

        return $this->back('请求成功', '200', $result);

    }

    public function IsToken(){
        $param = $this->request->all();

        // var_dump($this->model);
        // $result = $this->model->IsToken($params);
        if(!isset($param['token'])){
            return[
                'code' =>'error',
                'msg' =>'缺少token参数'
            ];
        }
        $token = $param['token'];
        $is_login = DB::table('users')->where('token',$token)->first();
        if(!$is_login){
            $result =  false;
        }
        $result = true;

        return $this->back('请求成功', '200', $result);
    }
    //获取亚马逊补货计划数据明细
    public function buhuoPlan_data()
    {
        $params = $this->request->all();

        $result = $this->model->buhuoPlan_data($params);

        return $this->back('请求成功', '200', $result);
    }

    //生成条形码
    public function make_CodeImg()
    {
        $params = $this->request->all();

        $result = $this->model->makeCodeImg($params);

        return $this->back('请求成功', '200', $result);
    }

    //生成库存条形码
    public function make_SkuCodeImg()
    {
        $params = $this->request->all();

        $result = $this->model->makeSkuCodeImg($params);

        return $this->back('请求成功', '200', $result);
    }
    
    public function GetErrInventory(){
        
        $params = $this->request->all();

        $result = $this->model->GetErrInventory($params);

        return $this->back('请求成功', '200', $result);
    }

    
    //获取数据单
    public function GetDataOrderList(){
        
        $params = $this->request->all();

        $result = $this->model->GetDataOrderListM($params);

        return $this->back('请求成功', '200', $result);
    }
    
    public function GetPdfNew(){
        
        $params = $this->request->all();

        $result = $this->model->GetPdfNew($params);

        if($result['type']!='fail'){
            return $this->back($result['msg'], '200', $result);
        }else{
            return $this->back($result['msg'], '500', $result);
        }

    }

    //亚马逊取消补货申请
    public function buhuoPlan_cancel()
    {
        try {
            $params = $this->request->all();
            $this->AddSysLog($params,'','亚马逊取消补货申请',__METHOD__);
            $id = $params['id'];
            db::beginTransaction();    //开启事务
            $buhuoRequestMdl = DB::table('amazon_buhuo_request')->where('id', '=', $id)->first();



            if (empty($buhuoRequestMdl)){
                db::rollback();
                return $this->back('未查询到计划Id：'.$id.'补货计划！', 500);
            }

            $d['user_id'] = $buhuoRequestMdl->request_userid;
            $d['out_no'] = $id;
            $d['create_time'] = date('Y-m-d H:i:s',time());
            $d['msg'] = '';
            db::table('inhouse_err_log')->insert($d);

            if ($buhuoRequestMdl->is_publish_fba == 1 && $buhuoRequestMdl->request_type == 1){
                $task_id = DB::table('tasks')
                    ->where('ext', 'like', "%$id%")
                    ->whereIn('class_id', [2, 3, 4])
                    ->where('is_deleted', 0)
                    ->select('Id','class_id')
                    ->first();

                // 判断是否存在合并的补货计划
                $childMdl = db::table('amazon_buhuo_request')
                    ->where('fid', $id)
                    ->get();

                if(!empty($task_id)) {
                    if ($task_id->class_id == 2) {
                        if ($buhuoRequestMdl->request_status > 3) {
                            //如果是云仓计划则加入取消订单队列
                            $job['order_no'] = $id;
                            $job['order_type'] = 'B2BCK';
                            $cloud = new \App\Http\Controllers\Jobs\CloudHouseController();
                            try {
                                $cloud::cancelJob($job);
                            } catch (\Exception $e) {
                                Redis::Lpush('order_cancel_fail', json_encode($job));
                            }
                        }
                        db::commit();
                        return $this->back('取消请求已提交，等待云仓响应', '200');
                    } else {
                        $goods = DB::table('goods_transfers')->where('order_no', '=', $id)->select('is_push')->first();
                        if (empty($goods)) {
//                            $res = DB::table('amazon_buhuo_request')->where('id', '=', $id)->update(['request_status' => 1]);
//                            if (!$res) {
//                                db::rollback();// 回调
//                                return $this->back('取消失败-amazon_buhuo_request', '500');
//                            }
//                            db::commit();
                            db::rollback();
                            return $this->back('数据异常！无goods_transfers数据！', '500');
                        }
                        if ($goods->is_push == 4) {
                            db::rollback();
                            return $this->back('订单已开始流转，无法取消', '500');
                        }
                        if ($childMdl->isNotEmpty()) {
                            $res = DB::table('amazon_buhuo_request')->where('id', '=', $id)->delete();
                            if (!$res) {
                                db::rollback();// 回调
                                return $this->back('删除失败-amazon_buhuo_request', '500');
                            }
                            $res = DB::table('amazon_buhuo_detail')->where('request_id', '=', $id)->delete();
                            if (!$res) {
                                db::rollback();// 回调
                                return $this->back('删除失败-amazon_buhuo_detail', '500');
                            }
                            $goods_update = DB::table('goods_transfers')->where('order_no', '=', $id)->delete();
                            if (!$goods_update) {
                                db::rollback();// 回调
                                return $this->back('删除失败-goods_transfers表', '500');
                            }
                            $delete = db::table('goods_transfers_detail')
                                ->where('order_no', '=', $id)
                                ->delete();
                            if (!$delete) {
                                db::rollback();// 回调
                                return $this->back('删除失败-goods_transfers_detail', '500');
                            }
                            $boxMdl = db::table('goods_transfers_box')
                                ->where('order_no', '=', $id)
                                ->first();
                            if (!empty($boxMdl)) {
                                $delete = db::table('goods_transfers_box')
                                    ->where('order_no', '=', $id)
                                    ->delete();
                                $delete = db::table('goods_transfers_box_detail')
                                    ->where('box_id', '=', $boxMdl->id)
                                    ->delete();
                            }

                            $del = DB::table('tasks')->where('Id', $task_id->Id)->update(['is_deleted' => 1]);
                            if (!$del) {
                                db::rollback();// 回调
                                return $this->back('删除失败-goods_transfers_detail', '500');
                            }
                            $msg = '';
                            foreach ($childMdl as $ch) {
                                $update = db::table('amazon_buhuo_request')
                                    ->where('id', $ch->id)
                                    ->update(
                                        [
                                            'fid' => 0,
                                            'is_publish_fba' => 0
                                        ]
                                    );
                                if (empty($update)) {
                                    $msg .= '计划Id：' . $ch->id . '取消fba出库单更新推送状态失败！';
                                }
                                $update = db::table('goods_transfers')
                                    ->where('order_no', $ch->id)
                                    ->update(['is_push' => 2]);
                                if (empty($update)) {
                                    $msg .= '计划Id：' . $ch->id . '取消fba出库单更新推送状态失败！';
                                }
                                $update = db::table('goods_transfers_box')
                                    ->where('order_no', $ch->id)
                                    ->update(['is_delete' => 0]);
                                if (empty($update)) {
                                    $msg .= '计划Id：' . $ch->id . '删除中转箱失败！';
                                }
                            }
                            if (!empty($msg)){
                                db::rollback();// 回调
                                return $this->back('取消失败!原因：'.$msg, '500');
                            }
                        }else{
                            $res = DB::table('amazon_buhuo_request')->where('id', '=', $id)->update([
                                'fid' => 0,
                                'is_publish_fba' => 0
                            ]);
                            if(!$res){
                                db::rollback();// 回调
                                return $this->back('取消失败-amazon_buhuo_request', '500');
                            }
                            $goods_update = DB::table('goods_transfers')->where('order_no', '=', $id)->update([
                                'is_push' => 2,
                                'status' => 2
                            ]);
                            if(!$goods_update){
                                db::rollback();// 回调
                                return $this->back('取消失败-goods_transfers表', '500');
                            }
                            $del = DB::table('tasks')->where('Id', $task_id->Id)->update(['is_deleted' => 1]);
                        }

                        db::commit();
                        return $this->back('撤销成功！', '200');
                    }
                }else{
                    db::rollback();// 回调
                    return $this->back('未查询到计划Id：'.$id.'的fba出库任务！', '500');
                }

            }else {
                $task_id = DB::table('tasks')
                    ->where('ext', 'like', "%$id%")
                    ->whereIn('class_id', [124, 127])
                    ->where('is_deleted', 0)
                    ->select('Id','class_id')
                    ->first();
                if(!empty($task_id)){
                    if($task_id->class_id==2){
                        if($buhuoRequestMdl->request_status>3){
                            //如果是云仓计划则加入取消订单队列
                            $job['order_no'] = $id;
                            $job['order_type'] = 'B2BCK';
                            $cloud = new \App\Http\Controllers\Jobs\CloudHouseController();
                            try {
                                $cloud::cancelJob($job);
                            } catch(\Exception $e){
                                Redis::Lpush('order_cancel_fail',json_encode($job));
                            }
                        }
                        db::commit();
                        return $this->back('取消请求已提交，等待云仓响应', '200');
                    }else{
                        $goods = DB::table('goods_transfers')->where('order_no', '=', $id)->select('is_push')->first();
                        if (empty($goods)){
                            $res = DB::table('amazon_buhuo_request')->where('id', '=', $id)->update(['request_status' => 1]);
                            if(!$res){
                                db::rollback();// 回调
                                return $this->back('取消失败-amazon_buhuo_request', '500');
                            }
                            $del = DB::table('tasks')->where('Id', $task_id->Id)->update(['is_deleted' => 1]);
                            if(!$res){
                                db::rollback();// 回调
                                return $this->back('删除失败-tasks', '500');
                            }
                            db::commit();
                            return $this->back('取消成功', '200');
                        }
                        if($goods->is_push==4){
                            return $this->back('订单已开始流转，无法取消', '500');
                        }

                        $res = DB::table('amazon_buhuo_request')->where('id', '=', $id)->update(['request_status' => 1]);
                        if(!$res){
                            db::rollback();// 回调
                            return $this->back('取消失败-amazon_buhuo_request', '500');
                        }
                        $goods_update = DB::table('goods_transfers')->where('order_no', '=', $id)->update(['is_push' => -1]);
                        if(!$goods_update){
                            db::rollback();// 回调
                            return $this->back('取消失败-goods_transfers表', '500');
                        }
                        DB::table('goods_transfers_box')->where('order_no',$id)->update(['is_delete'=>1]);
                        $del = DB::table('tasks')->where('Id', $task_id->Id)->update(['is_deleted' => 1]);

//                $box = DB::table('goods_transfers_box')->where('order_no',$id)->select('id')->first();
//                if(!empty($box)){
//                    $box_data = DB::table('goods_transfers_box_detail')->where('box_id',$box->id)->select('custom_sku_id','box_num','location_ids','shelf_num')->get();
//                    foreach ($box_data as $bb){
//                        if($bb->shelf_num>0){
//                            db::rollback();// 回调
//                            return $this->back('订单已开始流转，无法取消', '500');
//                        }
//                    }
//                    DB::table('goods_transfers_box')->where('id',$box->id)->update(['is_delete'=>1]);
//                }else{
//                    db::rollback();// 回调
//                    return $this->back('取消失败，没有查到出库任务箱号', '500');
//                }
                        db::commit();
                        return $this->back('取消成功', '200');
                    }
                }else{
                    if($buhuoRequestMdl->request_status>3&&$buhuoRequestMdl->warehouse==3){
                        //如果是云仓计划则加入取消订单队列
                        $job['order_no'] = $id;
                        $job['order_type'] = 'B2BCK';
                        $cloud = new \App\Http\Controllers\Jobs\CloudHouseController();
                        try {
                            $cloud::cancelJob($job);
                        } catch(\Exception $e){
                            Redis::Lpush('order_cancel_fail',json_encode($job));
                        }
                        db::commit();
                        return $this->back('取消请求已提交，等待云仓响应', '200');
                    }else{
                        $res = DB::table('amazon_buhuo_request')->where('id', '=', $id)->update(['request_status' => 1]);
                        if(!$res){
                            db::rollback();// 回调
                            return $this->back('取消失败-amazon_buhuo_request', '500');
                        }
                        $goods = DB::table('goods_transfers')->where('order_no', '=', $id)->update(['is_push' => -1]);
                        if(!$goods){
                            db::rollback();// 回调
                            return $this->back('取消失败-goods_transfers表', '500');
                        }
                        DB::table('goods_transfers_box')->where('order_no',$id)->update(['is_delete'=>1]);
                        db::commit();
                        return $this->back('取消成功', '200');
                    }
                }
            }
        }catch (\Exception $e){
            return $this->back('取消失败'.$e->getMessage().'；位置：'.$e->getLine(), '500');
        }


    }

    //亚马逊确认出库
    public function buhuoPlan_success()
    {
        $params = $this->request->all();
        $token = $params['token'];
        $user_data = DB::table('users')->where('token', '=', $token)->select('Id')->first();
        $user_id = $user_data->Id;
        $id = $params['id'];
        $box_data = DB::table('goods_transfers_box')->where('order_no',$id)->select('box_num','onshelf_num')->first();

            $request_id_json = substr(substr(json_encode(array("request_id" => "{$id}")), 1), 0, -1);
            $task_data = Db::table('tasks')
                ->where('ext', 'like', "%{$request_id_json}%")
                ->where('state','!=',2)
                ->whereIn('class_id', [2, 3, 4, 124])
                ->where('is_deleted', 0)
                ->select('Id', 'name', 'user_fz','class_id')
                ->get()
                ->toArray();
            if ($task_data) {
                $task_id = $task_data[0]->Id;
            }

            if($task_data[0]->class_id!=124){
                if(empty($box_data)){
                    return $this->back('未生成中装箱任务，请联系技术部门', '500');
                }
            }
//            $task_node_data = Db::table('tasks_node')->where(['task_id' => $task_id])->get()->toArray();
//            $time = date('Y-m-d H:i:s', time());
//            $update_task = Db::table('tasks_node')->where('Id', $task_node_data[2]->Id)->update(['state' => 3, 'time_end' => $time]);
            $task_son = Db::table('tasks_son')->select('Id', 'user_id','state')->where(['task_id' => $task_id])->get()->toArray();
            $taskArr['state'] = 3;
            $taskArr['feedback_type'] = 1;
            $taskArr['feedback_content'] = isset($params['remark']) ? $params['remark'] : '';
            $call_task = new \App\Libs\wrapper\Task();
            $datetime = date('Y-m-d H:i:s');
            db::beginTransaction();
            $task_state = 0;

            if($task_data[0]->class_id!=124){
                $taskArr['Id'] = $task_son[2]->Id;
                $task_state = $task_son[2]->state;
            }else{
                $taskArr['Id'] = $task_son[3]->Id;
                $task_state = $task_son[3]->state;
            }


            if($task_state==1){
                return $this->back('请先接受确认出库任务', '500');
            }elseif ($task_state==2) {
                $return = $call_task->task_son_complete($taskArr);
                if ($return == 1) {
                    $update_request = Db::table('amazon_buhuo_request')->where('id', $id)->update(['request_status' => 8,'over_time'=>$datetime]);

                    $detail =  Db::table('amazon_buhuo_detail')->where('request_id', $id)->get();
                    $detailJson = json_decode(json_encode($detail),true);

                    $skuArr = array_column($detailJson,'custom_sku_id');
                    $self_custom_sku = DB::table('self_custom_sku')->whereIn('id',$skuArr)->select('id','quanzhou_inventory','tongan_inventory','deposit_inventory','type','custom_sku','direct_inventory')->get();
                    $sku_id = array();

                    foreach ($self_custom_sku as $s){
                        $sku_id[$s->id] = $s;
                    }


                    $request =  Db::table('amazon_buhuo_request')->where('id', $id)->select('warehouse','shop_id')->first();
                    if(!empty($detail)){
                        $total_num = 0;
                        $basemodel = new BaseModel();
                        if($task_data[0]->class_id==124){
                            $cloudhouse_warehouse = DB::table('cloudhouse_warehouse_location as a')
                                ->leftJoin('suppliers as b','a.location_name','=','b.supplier_no')
                                ->where('a.level',3)
                                ->where('b.Id',$detail[0]->supplier_id)
                                ->select('a.id')
                                ->first();
                            if(empty($cloudhouse_warehouse)){
                                return $this->back('没有此供应商的库位数据,无法出库', '500');
                            }
                        }


                        foreach ($detail as $d){
                            $onbox_num = json_decode($d->box_data_detail,true);
                            $d->onbox_num = array_sum($onbox_num);
//                            if($sku_id[$d->custom_sku_id]->type==2){
//                                $group = $basemodel->GetGroupCustomSku($d->custom_sku);
//                                $group = array_column($group,'group_custom_sku');
//                                foreach ($group as $v) {
//                                    # code...
//                                    $group_inventory = $basemodel->getBuhuoByCusB($v);
//                                    if($group_inventory){
//                                        if($request->warehouse==1) {
//                                            $balance = $group_inventory['tongAn_inventory'];
//                                            $update_num['tongan_inventory'] = $balance-$d->onbox_num;
//                                        }
//                                        if($request->warehouse==2){
//                                            $balance = $group_inventory['quanzhou_inventory'];
//                                            $update_num['quanzhou_inventory'] = $balance-$d->onbox_num;
//                                        }
//                                        if($request->warehouse==6){
//                                            $balance = $group_inventory['deposit_inventory'];
//                                            $update_num['deposit_inventory'] = $balance-$d->onbox_num;
//                                        }
//                                        if($balance-$d->onbox_num<0){
//                                            db::rollback();// 回调
//                                            $this->back('库存不足--'.$v, '500');
//                                        }
//                                        Db::table('self_custom_sku')->where('id', $group_inventory['id'])->update($update_num);
//
//                                        $query['warehouse_id'] = $request->warehouse;
//                                        $query['custom_sku_id'] = $group_inventory['id'];
//                                        $query['price'] = $basemodel->GetCloudHousePrice($request->warehouse,$group_inventory['id']);
//                                        $query['num'] = $d->onbox_num;
//                                        $query['user_id'] = $user_id;
//                                        $query['type'] = 1; //1为出2为入
//                                        $res = $basemodel->UpCloudHousePrice($query);
//                                        if($res['type']!='success'){
//                                            db::rollback();// 回调
//                                            $this->back('新增资产记录失败--'.$v, '500');
//                                        }
//                                        //改动结束
//
//                                        $insert['custom_sku'] = $v;
//                                        $insert['type'] = 1;
//                                        $insert['order_no'] = $id;
//                                        $insert['num'] = $d->onbox_num;
//                                        $insert['custom_sku_id'] = $group_inventory['id'];
//                                        $insert['spu_id'] = $group_inventory['spu_id'];
//                                        $insert['spu'] = $group_inventory['spu'];
//                                        $insert['createtime'] = $datetime;
//                                        $insert['warehouse_id'] = $request->warehouse;
//                                        $insert['type_detail'] = 6;
//                                        $insert['user_id'] = $user_id;
//                                        $insert['shop_id'] =  $request->shop_id;
//                                        //仓储改动
//                                        $insert['price'] = $query['price'];
//                                        $insert['now_inventory'] = $balance-$d->onbox_num;
//                                        $insert['now_total_price'] = $res['total_price'];
//                                        //改动结束
//                                        $insert_record = DB::table('cloudhouse_record')->insert($insert);
//                                    }
//                                }
//                                DB::table('goods_transfers_detail')->where('order_no',$id)->where('custom_sku_id',$d->custom_sku_id)->update(['receive_num'=>$d->onbox_num]);
//                                $total_num += $d->onbox_num;
//                            }
//                              else{
                                //仓储改动
                                if($request->warehouse==1) {
                                    if(isset($sku_id[$d->custom_sku_id])){
                                        $balance = $sku_id[$d->custom_sku_id]->tongan_inventory;
                                        $update_num['tongan_inventory'] = $balance-$d->onbox_num;
                                        $sku_id[$d->custom_sku_id]->tongan_inventory = $balance-$d->onbox_num;
                                    }else{
                                        db::rollback();// 回调
                                        $this->back('库存扣减失败--'.$d->custom_sku, '500');
                                    }
                                }
                                if($request->warehouse==2){
                                    if(isset($sku_id[$d->custom_sku_id])){
                                        $balance = $sku_id[$d->custom_sku_id]->quanzhou_inventory;
                                        $update_num['quanzhou_inventory'] = $balance-$d->onbox_num;
                                        $sku_id[$d->custom_sku_id]->quanzhou_inventory = $balance-$d->onbox_num;
                                    }else{
                                        db::rollback();// 回调
                                        $this->back('库存扣减失败--'.$d->custom_sku, '500');
                                    }
                                }
                                if($request->warehouse==21){
                                    if(isset($sku_id[$d->custom_sku_id])){
                                        $balance = $sku_id[$d->custom_sku_id]->direct_inventory;
                                        $update_num['direct_inventory'] = $balance-$d->onbox_num;
                                        $sku_id[$d->custom_sku_id]->direct_inventory = $balance-$d->onbox_num;
                                    }else{
                                        db::rollback();// 回调
                                        $this->back('库存扣减失败--'.$d->custom_sku, '500');
                                    }
                                    $location_num = DB::table('cloudhouse_location_num')
                                        ->where('location_id',$cloudhouse_warehouse->id)
                                        ->where('custom_sku_id',$d->custom_sku_id)
                                        ->select('num','id','platform_id')
                                        ->get()->toArray();
                                    $location_total = 0;
                                    $amazon_num = 0;
                                    $updateId = 0;
                                    foreach ($location_num as $n){
                                        $location_total+=$n->num;
                                        if($n->platform_id==5){
                                            $amazon_num = $n->num;
                                            $updateId = $n->id;
                                        }
                                    }
                                    if($d->onbox_num>$amazon_num){
                                        db::rollback();// 回调
                                        $this->back('库位库存不足--'.$d->custom_sku, '500');
                                    }else{
                                        if($updateId!=0){
                                            $log['spu'] = $d->spu;
                                            $log['spu_id'] = $d->spu_id;
                                            $log['custom_sku_id'] = $d->custom_sku_id;
                                            $log['custom_sku'] = $d->custom_sku;
                                            $log['num'] = $d->onbox_num;
                                            $log['location_id'] = $cloudhouse_warehouse->id;
                                            $log['time'] = $datetime;
                                            $log['type'] = 2;
                                            $log['order_no'] = $d->request_id;
                                            $log['user_id'] = $user_id;
                                            $log['platform_id'] = 5;
                                            $log['now_num'] = $location_total-$d->onbox_num;
                                            $log['now_platform_num'] = $amazon_num-$d->onbox_num;
                                            DB::table('cloudhouse_location_num')->where('id',$updateId)->update(['num'=>$location_total - $d->onbox_num]);
                                            $insertlog = DB::table('cloudhouse_location_log')->insert($log);
                                        }
                                    }
                                }
                                if($balance-$d->onbox_num<0){
                                    db::rollback();// 回调
                                    $this->back('库存不足--'.$d->custom_sku, '500');
                                }


                                Db::table('self_custom_sku')->where('id', $d->custom_sku_id)->update($update_num);

                                $query['warehouse_id'] = $request->warehouse;
                                $query['custom_sku_id'] = $d->custom_sku_id;
                                $query['price'] = $basemodel->GetCloudHousePrice($request->warehouse,$d->custom_sku_id);
                                $query['num'] = $d->onbox_num;
                                $query['user_id'] = $user_id;
                                $query['type'] = 1; //1为出2为入
                                $res = $basemodel->UpCloudHousePrice($query);
                                if($res['type']!='success'){
                                    db::rollback();// 回调
                                    $this->back('新增资产记录失败--'.$d->custom_sku, '500');
                                }
                                //改动结束

                                $insert['custom_sku'] = $d->custom_sku;
                                $insert['type'] = 1;
                                $insert['order_no'] = $id;
                                $insert['num'] = $d->onbox_num;
                                $insert['custom_sku_id'] = $d->custom_sku_id;
                                $insert['spu_id'] = $d->spu_id;
                                $insert['spu'] = $d->spu;
                                $insert['createtime'] = $datetime;
                                $insert['warehouse_id'] = $request->warehouse;
                                $insert['type_detail'] = 6;
                                $insert['user_id'] = $user_id;
                                $insert['shop_id'] =  $request->shop_id;
                                //仓储改动
                                $insert['price'] = $query['price'];
                                $insert['now_inventory'] = $balance-$d->onbox_num;
                                $insert['now_total_price'] = $res['total_price'];
                                //改动结束
                                $insert_record = DB::table('cloudhouse_record')->insert($insert);
                                DB::table('goods_transfers_detail')->where('order_no',$id)->where('custom_sku_id',$d->custom_sku_id)->update(['receive_num'=>$d->onbox_num]);
                                $total_num += $d->onbox_num;
//                            }
                        }
                        if($task_data[0]->class_id!=124){
                            $goods_transfers_box = Db::table('goods_transfers_box')->where('order_no',$id)->select('onshelf_num','status','box_num')->first();
                            if(empty($goods_transfers_box)){
                                db::rollback();// 回调
                                return $this->back('未查询到此出库单得任务数据', '500');
                            }
                        }
                        //仓储改动
                        $update_goods = Db::table('goods_transfers')->where('order_no', $id)->update(['is_push' => 3,'confirm_id'=>$user_id,
                            'receive_total_num'=>$total_num,'out_house_time'=>$datetime,'sj_arrive_time'=>$datetime]);
                        //改动结束
                    }else{
                        db::rollback();// 回调
                        return $this->back('未查询到此出库单数据', '500');
                    }

                    db::commit();
                    return $this->back('已确认出库', '200');
                } else {
                    db::rollback();// 回调
                    return $this->back('确认出库失败', '500');
                }
            }else{
                return $this->back('任务状态错误，确认出库失败', '500');
            }


//            $update_task_son = Db::table('tasks')->where('Id', $task_id)->update(['state' => 4, 'time_end' => $time]);
//            $update_task_son = Db::table('tasks_son')->where('Id', $task_son[2]->Id)->update(['state' => 3, 'time_end_sj' => $time]);
//            $update_task_son = Db::table('tasks_son')->where('Id', $task_son[3]->Id)->update(['state' => 2, 'time_end_sj' => $time]);
//            $update_task = Db::table('tasks_node')->where('Id', $task_node_data[3]->Id)->update(['state' => 2, 'time_end' => $time]);
            //发站内消息给负责人提示验收
//            $content = "任务：{$task_data[0]->name}，确认出库完成,请及时填写物流信息！";
//            $sql = "insert into tidings(`user_fs`, `user_js`, `title`, `content`, `object_id`, `object_type`, `type`, `create_time`)
//						values (0, {$task_son[3]->user_id}, '确认出库完成', '{$content}', {$task_id}, 1, 1, '{$time}')";
//            db::insert($sql);

    }

    //亚马逊重新提交补货申请
    public function buhuoPlan_again()
    {
        $params = $this->request->all();

        $id = $params['id'];

        $res = DB::table('amazon_buhuo_request')->where('id', '=', $id)->update(['request_status' => 2]);

        $goods = DB::table('goods_transfers')->where('order_no', '=', $id)->update(['is_push' => 2]);

        if ($res) {
            return $this->back('重新提交成功', '200');
        } else {
            return $this->back('重新提交失败', '200');
        }

    }

    //亚马逊修改补货单补货数量
    public function update_buhuoNum()
    {
        $params = $this->request->all();
        $data = $params['data'];
        $request_id = $params['request_id'];
        $requestMdl = $this->amazonBuhuoRequestModel::query()
            ->where('id', $request_id)
            ->first();
        if (empty($requestMdl)){
            return $this->back('修改失败，没有查询到该补货单数据', '300');
        }
        $transportationMdl = $this->transportationModeModel::query()
            ->where('name', $requestMdl->transportation_mode_name)
            ->first();
        if (empty($transportationMdl)){
            return $this->back('修改失败，没有查询到运输方式信息', '300');
        }
        if(empty($data)){
            return $this->back('修改失败，没有修改数据', '300');
        }else{
            db::beginTransaction();    //开启事务
            foreach ($data as $val){
                if (empty($val['id']) && empty($val['request_num'])) {
                    db::rollback();// 回调
                    return $this->back('修改失败，参数不足', '300');
                }else{
                    $res = DB::table('amazon_buhuo_detail')->where('id', '=', $val['id'])->update(['request_num' => $val['request_num']]);
                    if (!$res) {
                        db::rollback();// 回调
                        return $this->back('修改失败,amazon_buhuo_detail表', '300');
                    }
                }
            }
            $transportation_date = date("Y-m-d", strtotime("+{$transportationMdl->expected_duration} day"));
            $update = array();
            if(isset($transportation_date)) $update['transportation_date'] = $transportation_date;
            $update_date = DB::table('amazon_buhuo_request')->where('id', '=', $request_id)->update($update);
            db::commit();// 确认
            return $this->back('修改成功', '200');
        }
        if (empty($params['id']) && empty($params['courier_num']) && empty($params['shipping_num']) && empty($params['air_num'])) {
            return $this->back('修改失败，参数不足', '200');
        } else {
            $res = DB::table('amazon_buhuo_detail')->where('id', '=', $id)->update(['courier_num' => $params['courier_num'], 'shipping_num' => $params['shipping_num'], 'air_num' => $params['air_num']]);
            if ($res) {
//                $delivery_date = date('Y-m-d');
                $courier_arr = array();
                $shipping_arr = array();
                $air_arr = array();
                $courier_date = '1970-01-01';
                $shipping_date = '1970-01-01';
                $air_date = '1970-01-01';
                $data = DB::table('amazon_buhuo_detail')->where('request_id', '=', $request_id)->select('courier_num', 'shipping_num', 'air_num')->get();
                foreach ($data as $val) {
                    $courier_arr[] = $val->courier_num;
                    $shipping_arr[] = $val->shipping_num;
                    $air_arr[] = $val->air_num;
                }
                $courier_total = array_sum($courier_arr);
                $shipping_total = array_sum($shipping_arr);
                $air_total = array_sum($air_arr);
                if ($courier_total != 0) {
                    $courier_date = date("Y-m-d", strtotime("+5 day"));
                }
                if ($shipping_total != 0) {
                    $shipping_date = date("Y-m-d", strtotime("+30 day"));
                }
                if ($air_total != 0) {
                    $air_date = date("Y-m-d", strtotime("+15 day"));
                }
                DB::table('amazon_buhuo_request')->where('id', '=', $request_id)->update(['courier_date' => $courier_date, 'shipping_date' => $shipping_date, 'air_date' => $air_date]);
                return $this->back('修改成功', '200');

            } else {
                return $this->back('修改失败', '300');
            }
        }

    }

    //亚马逊修改补货单各日期、物流单号
    public function update_buhuoDate()
    {
        $params = $this->request->all();
//        var_dump($params);die;
        $id = $params['request_id'];
        if (isset($params['request_status']) && $params['request_status'] < 8) {
            return $this->back('状态为已确认出库，待发货才能修改物流单号', '300');
        }
        if (isset($params['logistics_order_no'])) {
            $update['logistics_order_no'] = implode(',', array_column($params['logistics_order_no'], 'value'));
        } elseif (isset($params['logistics_price'])) {
            $update['logistics_price'] = $params['logistics_price'];
        } elseif (isset($params['calculate_heavy'])) {
            $update['calculate_heavy'] = $params['calculate_heavy'];
        } else {
            if (isset($params['transport_type'])) {
                $transportationMdl = $this->transportationModeModel::query()
                    ->where('name', $params['transport_type'])
                    ->first();
                if (empty($transportationMdl)){
                    return $this->back('修改失败，没有查询到运输方式信息', '300');
                }
                $update['transportation_date'] = date("Y-m-d", strtotime("+{$transportationMdl->expected_duration} day", strtotime($params['delivery_date'])));;
            }
            $update['delivery_date'] = $params['delivery_date'];

        }

        if (!empty($id)) {
            db::beginTransaction();    //开启事务
            $res = DB::table('amazon_buhuo_request')->where('id', '=', $id)->update($update);
            $taskArr['state'] = 3;
            $taskArr['feedback_type'] = 1;
            $call_task = new \App\Libs\wrapper\Task();

            if ($res) {
                if (isset($params['logistics_order_no'])) {
                    if (isset($params['request_status']) && $params['request_status'] >= 8 && $params['request_status'] < 10) {
                        foreach ($params['logistics_order_no'] as $v){
                            // 保存物流单号
                            DB::table('amazon_create_goods')
                                ->where('id', $v['id'])
                                ->update(['logistics_order_no' => $v['value']]);
                        }
                        $update_request = Db::table('amazon_buhuo_request')->where('id', $id)->update(['request_status' => 9]);

                        $request_id_json = substr(substr(json_encode(array("request_id" => "{$id}")), 1), 0, -1);
                        $task_data = Db::table('tasks')
                            ->where('ext', 'like', "%{$request_id_json}%")
                            ->where('state','!=',2)
                            ->where('is_deleted', 0)
                            ->where('class_id', '<>', 127)
                            ->select('Id', 'name', 'user_fz','class_id')->get()->toArray();
                        if ($task_data) {
                            $task_id = $task_data[0]->Id;
                        }
                        $task_son = Db::table('tasks_son')->select('Id', 'user_id','state')->where(['task_id' => $task_id])->get()->toArray();


                        if($task_son[3]->state==1){
                            db::rollback();// 回调
                            return $this->back('修改失败,请先接受任务', '300');
                        }
                        $taskArr['Id'] = $task_son[3]->Id;
                        $return = $call_task->task_son_complete($taskArr);
                        db::commit();// 确认
                        if ($return !=1) {
                            return $this->back('修改成功，但物流任务自动完成失败,请手动去我的任务完成', '500');
                        }
                    }else{
                        db::commit();// 确认
                    }
                    return $this->back('修改成功', '200');
                }else{
                    db::commit();// 确认
                    return $this->back('修改成功', '200');
                }
            } else {
                db::rollback();// 回调
                return $this->back('修改失败', '300');
            }

        }
    }

    //亚马逊删除补货单补货数量
    public function buhuoNum_delete()
    {
//        return $this->back('删除功能维护中...', 500);
        $params = $this->request->all();
        $id = $params['id'];
        $request_id = $params['request_id'];
        if (empty($id)) {
            return $this->back('删除失败，没有id', '500');
        } else {
            db::beginTransaction();    //开启事务
            $res = DB::table('amazon_buhuo_detail')->where('id', '=', $id)->delete();
            if ($res) {
                $detail = DB::table('amazon_buhuo_detail')->where('id', '=', $id)->select('custom_sku_id','request_num')->first();
                $deleteDetail = DB::table('goods_transfers_detail')->where('order_no', '=', $request_id)->where('custom_sku_id',$detail->custom_sku_id)
                    ->where('transfers_num', $detail->request_num)->delete();
                if(!$deleteDetail){
                    db::rollback();// 回调
                    return $this->back('goods_transfers_detail表数据删除失败', '200');
                }
                $Box = DB::table('goods_transfers_box')->where('order_no', '=', $request_id)->select('id','box_num')->first();
                if(!empty($Box)){
                    $deleteBox = DB::table('goods_transfers_box_detail')->where('box_id', '=', $Box->id)->where('custom_sku_id',$detail->custom_sku_id)->delete();
                    if(!$deleteBox){
                        db::rollback();// 回调
                        return $this->back('goods_transfers_box_detail表数据删除失败', '200');
                    }
                    DB::table('goods_transfers_box')->where('id', '=', $Box->id)->update(['box_num'=>$Box->box_num - $detail->request_num]);
                }
                $courier_arr = array();
                $shipping_arr = array();
                $air_arr = array();
                $courier_date = '1970-01-01';
                $shipping_date = '1970-01-01';
                $air_date = '1970-01-01';
                $data = DB::table('amazon_buhuo_detail')->where('request_id', '=', $request_id)->select('courier_num', 'shipping_num', 'air_num')->get();
                foreach ($data as $val) {
                    $courier_arr[] = $val->courier_num;
                    $shipping_arr[] = $val->shipping_num;
                    $air_arr[] = $val->air_num;
                }
                $courier_total = array_sum($courier_arr);
                $shipping_total = array_sum($shipping_arr);
                $air_total = array_sum($air_arr);
                if ($courier_total != 0) {
                    $courier_date = date("Y-m-d", strtotime("+5 day"));
                }
                if ($shipping_total != 0) {
                    $shipping_date = date("Y-m-d", strtotime("+30 day"));
                }
                if ($air_total != 0) {
                    $air_date = date("Y-m-d", strtotime("+15 day"));
                }
                DB::table('amazon_buhuo_request')->where('id', '=', $request_id)->update(['courier_date' => $courier_date, 'shipping_date' => $shipping_date, 'air_date' => $air_date]);
                db::commit();// 确认
                return $this->back('删除成功', '200');
            } else {
                db::rollback();// 回调
                return $this->back('删除失败', '500');
            }
        }

    }

    //根据获取的sku查找可能需要补货的sku
    public function may_buhuo()
    {
        $params = $this->request->all();

        $result = $this->model->may_buhuo($params);

        return $this->back('请求成功', '200', $result);

    }

    //新增创货件信息
    public function create_goods()
    {
        $params = $this->request->all();
        $result = $this->model->create_goods($params);

        if ($result['type'] == 'success') {
            return $this->back($result['msg'], '200');
        } else {
            return $this->back($result['msg'], '300');
        }
    }

    //查询所有创货件信息
    public function select_createGoods()
    {
        $params = $this->request->all();

        $result = $this->model->select_createGoods($params);

        return $this->back('请求成功', '200', $result);

    }

    //查询所有创货件信息
    public function update_createGoods()
    {
        $params = $this->request->all();

        $result = $this->model->update_createGoods($params);

        if ($result['type'] == 'success') {
            return $this->back($result['msg'], '200');
        } else {
            return $this->back($result['msg'], '300');
        }

    }

    //保存装箱数据
    public function save_box_data()
    {
        $params = $this->request->all();

        $result = $this->model->save_box_data($params);

        $this->AddSysLog($params,$result,'补货保存装箱数据',__METHOD__);


        if ($result['type'] == 'success') {
            return $this->back($result['msg'], '200');
        } else {
            return $this->back($result['msg'], '300');
        }

    }


    //补货计划状态查询
    public function plan_status()
    {
        $status = Db::table('amazon_plan_status')->get()->toArray();
        if (is_array($status)) {
            $this->back('获取成功', '200', $status);
        } else {
            $this->back($status);
        }
    }

    //补货计划导出
    public function request_excel_export()
    {
        $params = $this->request->all();
        $result = $this->model->request_excel_export($params);
    }

    //补货详情导出
    public function detailed_excel_export()
    {
        $params = $this->request->all();
        $result = $this->model->detailed_excel_export($params);
    }

    //装箱单导出
    public function box_excel_export()
    {
        $params = $this->request->all();
        $result = $this->model->box_excel_export($params);
    }

    //生产下单数据
    public function production_order()
    {
        $params = $this->request->all();
        $result = $this->model->production_order($params);
        //var_dump($return);exit;
        if (is_array($result['list'])) {
            $this->back('获取成功', '200', $result);
        } else {
            $this->back($result);
        }
    }

    //生产下单任务列表
    public function AmazonSalesTaskList()
    {
        $params = $this->request->all();
        $result = $this->model->AmazonSalesTaskList($params);
        return $this->back('获取成功', '200', $result);
    }


    //生产下单导入
    public function production_excel_export()
    {
        $params['file'] = $_FILES['file'];
        if (empty($params['file'])) {
            $this->back('文件为空');
        }
        $result = $this->model->production_excel_export($params);

        if ($result['type'] == 'success') {
            return $this->back('导入成功', '200', $result['msg']);
        } else {
            return $this->back('导入失败', '500', $result['msg']);
        }
    }

    //亚马逊补货计划导出
    public function plan_excel_export()
    {
        $params = $this->request->all();
        if (!$params) {
            return '没有数据';
        }
        $result = $this->model->plan_excel_export($params);
    }

    //导出补货预警
    public function warning_export()
    {
        $params = $this->request->all();
        $result = $this->model->warning_export($params);

    }

    //上传pdf
    public function add_pdf()
    {
        $params = $this->request->all();

        $result = $this->model->add_pdf($params);

        if ($result['type'] == 'success') {
            return $this->back($result['data'], '200');
        } else {
            return $this->back($result['msg'], '300');
        }
    }

    //亚马逊创货件pdf是否打开
    public function set_pdf_status()
    {
        $params = $this->request->all();
        $token = $params['token'];
        $id = $params['id'];
        //根据token识别申请人
        $user_data = DB::table('users')->where('token', '=', $token)->select('Id', 'account')->get();
        if (!$user_data->isEmpty()) {
            $user_id = $user_data[0]->Id;
            $user_member = DB::table('organizes_member')->where('user_id', '=', $user_id)->select('organize_id')->get();
            if (!$user_member->isEmpty()) {
                $organize_id = $user_member[0]->organize_id;
                if ($organize_id == 22) {
                    $res = DB::table('amazon_create_goods')->where('id', '=', $id)->update(['pdf_status' => 1]);
                    if ($res) {
                        return $this->back('是仓库人员，修改状态为已打开', '200');
                    } else {
                        return $this->back('修改失败，未知错误', '500');
                    }
                } else {
                    return $this->back('不是仓库人员，不修改状i态', '500');
                }
            } else {
                return $this->back('此人没有组织', '500');
            }
        } else {
            return $this->back('没有此账号', '500');
        }
    }

//    public function delete_box(){
//        $params = $this->request->all();
//        $token = $params['token'];
//        $box_id = $params['box_id'];
//        $request_id = $params['request_id'];
//        //根据token识别申请人
//        $user_data = DB::table('users')->where('token', '=', $token)->select('Id', 'account')->get();
//        if (!$user_data->isEmpty()) {
//            $user_id = $user_data[0]->Id;
//            $user_member = DB::table('organizes_member')->where('user_id', '=', $user_id)->select('organize_id')->get();
//            if (!$user_member->isEmpty()) {
//                $organize_id = $user_member[0]->organize_id;
//                if ($organize_id == 22) {
//                    $box_data = DB::table('amazon_request_detail')->where('request_id', '=', $request_id)->select('box_data_detail')->get();
//                    if(!empty($box_data)){
//                         foreach ($box_data as $boxVal){
//
//                         }
//                    }else{
//                        return $this->back('没有装箱数据', '500');
//                    }
//                }else {
//                    return $this->back('不是仓库人员，不修改状态', '500');
//                }
//            }
//            else {
//                return $this->back('此人没有组织', '500');
//            }
//        }else {
//            return $this->back('没有此账号', '500');
//        }
//    }


    public function save_pdf_job(){

        $params = $this->request->all();

        $job = new SavePdfController();
        try {
            $job::runJob($params);
        } catch(\Exception $e){
            return $this->back('加入队列失败', 500);
        }

        return $this->back('加入队列成功', 200);
    }
    /**
     * 生成pdf
     */
    public function save_pdf()
    {

        $params = $this->request->all();
        $type = $params['type']??1;
        $plan_id = $params['plan_id'];
        ////权限验证
        $arr = array();
        $arr['user_id'] = $params['user_info']['user_id'];
        $arr['identity'] = array('amazon_pdf_update');
        $powers = $this->powers($arr);
        $is_update = 0;
        if ($powers['amazon_pdf_update'] && $params['request_status'] == 4) {
            $request_id_json = substr(substr(json_encode(array("request_id" => "{$plan_id}")), 1), 0, -1);
            $task_data = Db::table('tasks')->where('ext', 'like', "%{$request_id_json}%")->where('state','!=',2)->select('Id', 'name', 'user_fz')->get()->toArray();
            if ($task_data) $task_id = $task_data[0]->Id;
            $task_node_data = Db::table('tasks_node')->where(['task_id' => $task_id])->get()->toArray();
            $task_son_data = Db::table('tasks_son')->where(['task_id' => $task_id])->get()->toArray();
            $time = date('Y-m-d H:i:s', time());
            if($task_son_data[0]->state==1)return $this->back('请先接受盘点备货任务', '500');
            if($task_son_data[0]->state==2&&$task_son_data[0]->user_id == $params['user_info']['user_id']){
                $is_update = 1;
            }
        }
        $pdf = DB::table('save_pdf_log')->where('plan_id',$plan_id)->where('type',$type)->select('path')->orderby('id','desc')->first();
        if(!empty($pdf)){
            if($is_update==1)  $update_request = Db::table('amazon_buhuo_request')->where('id', $plan_id)->update(['request_status' => 5]);
            $url = $pdf->path.'?id='.rand(1,10000);
            return $this->back('请求成功', '200', array('url' => $url));
        }else{
            return $this->back('请求失败', '500');
        }
    }


    public function get_box_id(){
        $params = $this->request->all();
        $plan_id =  $params['plan_id'];
        $box = DB::table('amazon_box_data')->where('request_id',$plan_id)->select('box_id')->orderBy('box_id','ASC')->get()->toArray();
        $data = [];
        if(!empty($box)){
            foreach ($box as $v){
                $data[] = $v->box_id;
            }
        }
        return $this->back($data, '200');
    }


    //补货预警报表-新
    public function getBuhuoWarnNew()
    {
        $params = $this->request->all();
        $result = $this->model->getBuhuoWarnNew($params);
        if($result['type']=='success'){
            return $this->back('获取成功', '200', $result);
        }else{
            return $this->back($result['msg'], '300');
        }
    }

    //历史库存报表-库存
    public function getHisCusInventory()
    {
        $params = $this->request->all();
        $result = $this->model->getHisCusInventory($params);
        if($result['type']=='success'){
            return $this->back('获取成功', '200', $result);
        }else{
            return $this->back($result['msg'], '300');
        }
    }

    //历史库存报表-渠道
    public function getHisSkuInventory()
    {
        $params = $this->request->all();
        $result = $this->model->getHisSkuInventory($params);
        if($result['type']=='success'){
            return $this->back('获取成功', '200', $result);
        }else{
            return $this->back($result['msg'], '300');
        }
    }

    /**
     * @Desc:查询n天内店铺内款式补货数据
     * @param Request $request
     * @return null
     * @author: Liu Sinian
     * @Time: 2023/2/27 16:47
     */
    public function getLastMonthStyleReplenishList(Request $request)
    {
        $data = $request->all();
        $shopId = $data['shop_id'] ?? 0;
        $customSkuId = $data['custom_sku_id'] ?? [];
        $requestId = $data['request_id'] ?? 0;
        $day = $data['day'] ?? 30;
        $limit = $data['limit'] ?? 30;
        $page = $data['page'] ?? 1;
        $pageNum = $page <= 1 ? 0 : ($page-1)*$limit;
        $result = $this->model->getLastMonthStyleReplenishList($shopId, $customSkuId, $requestId, $day, $pageNum, $limit);

        return $this->back($result['msg'] ?? '', $result['code'] ?? 500, $result['data'] ?? []);
    }

    /**
     * @Desc: 保存运输方式
     * @return null
     * @author: Liu Sinian
     * @Time: 2023/4/3 15:08
     */
    public function saveTransportationMode()
    {
        $params = $this->request->all();
        $result = $this->model->saveTransportationMode($params);

        return $this->back($result['msg'] ?? '', $result['code'] ?? 500, $result['data'] ?? []);
    }

    /**
     * @Desc: 获取运输方式列表
     * @return null
     * @author: Liu Sinian
     * @Time: 2023/4/3 15:19
     */
    public function getTransportationModeList()
    {
        $params = $this->request->all();
        $result = $this->model->getTransportationModeList($params);

        return $this->back($result['msg'] ?? '', $result['code'] ?? 500, $result['data'] ?? []);
    }

    /**
     * @Desc: 删除运输方式（可批量）
     * @author: Liu Sinian
     * @Time: 2023/4/3 15:20
     */
    public function deleteTransportationMode()
    {
        $params = $this->request->all();
        $result = $this->model->deleteTransportationMode($params);

        return $this->back($result['msg'] ?? '', $result['code'] ?? 500, $result['data'] ?? []);
    }

    /**
     * @Desc: 更新补货请求和补货详情关于运输方式字段
     * @return null
     * @author: Liu Sinian
     * @Time: 2023/4/12 11:30
     */
    public function updateBuhuoRequestNum()
    {
        $params = $this->request->all();
        $result = $this->model->updateBuhuoRequestNum($params);

        return $this->back($result['msg'] ?? '', $result['code'] ?? 500, $result['data'] ?? []);
    }

    /**
     * @Desc:批量更新sku
     * @return null
     * @author: Liu Sinian
     * @Time: 2023/4/25 14:22
     */
    public function batchUpdateSkulist()
    {
        $params = $this->request->all();
        $result = $this->model->batchUpdateSkulist($params);

        return $this->back($result['msg'] ?? '', $result['code'] ?? 500, $result['data'] ?? []);
    }


    //获取pdf导出的减货数量
    public function GetPdfJonCusRes()
    {
        $params = $this->request->all();
        $result = $this->model->GetPdfJonCusRes($params);
        if($result['type']=='success'){
            return $this->back('获取成功', '200', $result);
        }else{
            return $this->back($result['msg'], '300');
        }
    }

    /**
     * @Desc:获取锁定库存详情
     * @return null
     * @author: Liu Sinian
     * @Time: 2023/6/25 15:27
     */
    public function getCustomSkuLockDetail()
    {
        $params = $this->request->all();
        $result = $this->model->getCustomSkuLockDetail($params);

        return $this->back($result['msg'] ?? '', $result['code'] ?? 500, $result['data'] ?? []);
    }

    public function checkFasinCodeStrategy()
    {
        $params = $this->request->all();
        $result = $this->model->checkFasinCodeStrategy($params);

        return $this->back($result['msg'] ?? '', $result['code'] ?? 500, $result['data'] ?? []);
    }

    /**
     * @Desc:保存补货装箱详情
     * @return null
     * @author: Liu Sinian
     * @Time: 2023/7/12 14:04
     */
    public function saveReplenishmentPackingDetail()
    {
        $params = $this->request->all();
        $result = $this->model->saveReplenishmentPackingDetail($params);

        $this->AddSysLog($params, $result, '保存补货装箱详情', __METHOD__);

        return $this->back($result['msg'] ?? '', $result['code'] ?? 500, $result['data'] ?? []);
    }

    /**
     * @Desc:获取补货装箱列表
     * @return null
     * @author: Liu Sinian
     * @Time: 2023/7/13 9:06
     */
    public function getReplenishmentPackingDetailList()
    {
        $params = $this->request->all();
        $result = $this->model->getReplenishmentPackingDetailList($params);

        return $this->back($result['msg'] ?? '', $result['code'] ?? 500, $result['data'] ?? []);
    }

    public function saveAmazonBoxData()
    {
        $params = $this->request->all();
        $result = $this->model->saveAmazonBoxData($params);
        $this->AddSysLog($params, $result, '保存补货装箱', __METHOD__);

        return $this->back($result['msg'] ?? '', $result['code'] ?? 500, $result['data'] ?? []);
    }

    /**
     * @Desc:删除装箱明细
     * @return null
     * @author: Liu Sinian
     * @Time: 2023/7/17 16:49
     */
    public function deleteReplenishmentPackingDetail(){
        $params = $this->request->all();
        $result = $this->model->deleteReplenishmentPackingDetail($params);
        $this->AddSysLog($params, $result, '删除补货装箱明细', __METHOD__);

        return $this->back($result['msg'] ?? '', $result['code'] ?? 500, $result['data'] ?? []);
    }

    /**
     * @Desc:补货请求合并fba发货
     * @author: Liu Sinian
     * @Time: 2023/11/1 16:24
     */
    public function buhuoRequestFbaShippment()
    {
        $params = $this->request->all();
        $result = $this->model->buhuoRequestFbaShippment($params);
        $this->AddSysLog($params, $result, '补货请求合并fba发货', __METHOD__);

        return $this->back($result['msg'] ?? '', $result['code'] ?? 500, $result['data'] ?? []);
    }

    /**
     * @Desc:修改补货数量
     * @return null
     * @author: Liu Sinian
     * @Time: 2023/11/29 14:21
     */
    public function updateBuhuoDetailRequestNum()
    {
        $params = $this->request->all();
        $result = $this->model->updateBuhuoDetailRequestNum($params);
        $this->AddSysLog($params, $result, '修改补货数量', __METHOD__);

        return $this->back($result['msg'] ?? '', $result['code'] ?? 500, $result['data'] ?? []);
    }

    /**
     * @Desc:进销存报表
     * @return null
     * @author: Liu Sinian
     * @Time: 2023/12/21 20:49
     */
    public function getInventoryReportList()
    {
        $params = $this->request->all();
        $result = $this->model->getInventoryReportList($params);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }
}
